package org.example.domain.order.service.mq_v2;


import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.domain.order.adapter.repository.IOrderRepository;
import org.example.domain.order.model.entity.DelayCancelOrderEntity;
import org.example.domain.order.model.entity.OrderEntity;
import org.example.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

import static org.example.types.common.MQConstants.DELAY_CANCEL_ORDER_CONSUMER_GROUP;
import static org.example.types.common.MQConstants.DELAY_CANCEL_ORDER_TOPIC;
import static org.example.types.enums.ResponseCode.ORDER_DB_UPDATE_ERROR;

/**
 * @author yinghuashen
 * @version 1.0
 * @description:
 * @date 2025/3/14 09:45
 */
@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = DELAY_CANCEL_ORDER_CONSUMER_GROUP,
        topic = DELAY_CANCEL_ORDER_TOPIC,
        messageModel = MessageModel.CLUSTERING
)
public class DelayCancelOrderTopicConsumer implements RocketMQListener<MessageExt> {

    @Resource
    private IOrderRepository orderRepository;

    @Override
    public void onMessage(MessageExt messageExt) {
        if(messageExt.getBody()==null){
            return;
        }
        DelayCancelOrderEntity delayCancelOrderEntity =
                JSONUtil.toBean(new String(messageExt.getBody(), StandardCharsets.UTF_8), DelayCancelOrderEntity.class);
        // 1. 获取订单号
        String orderId = delayCancelOrderEntity.getOrderId();
        log.info("DelayCancelOrderTopicConsumer 收到延时消息：userId = {}, orderId = {}",
                delayCancelOrderEntity.getUserId(), orderId);
        // 2. 查询订单状态
        int orderStatus = orderRepository.getOrderStatusById(orderId);
        // 3. 如果订单状态为待支付，则关闭订单，修改订单状态
        if(orderStatus == OrderEntity.OrderStatus.PENDING_PAYMENT.getCode()){
            log.info("DelayCancelOrderTopicConsumer OrderId = {}, 订单状态为：{}，超时关闭", orderId, orderStatus);
            // TODO 从缓存中删除用户购买名额
            // 关闭订单
            boolean res = orderRepository.closeDelayedOrder(orderId);
            if(!res){
                throw new AppException(ORDER_DB_UPDATE_ERROR);
            }
        }else{
            log.info("DelayCancelOrderTopicConsumer OrderId = {}, 订单状态为：{}，无需关闭", orderId, orderStatus);
        }
        // 4. 如果订单为其余状态，则直接忽略
    }
}
